package cn.pomelo.album.controller;

import cn.pomelo.album.commom.AjaxResult;
import cn.pomelo.album.commom.FileUtil;
import cn.pomelo.album.model.Image;
import cn.pomelo.album.service.ImageService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/file")
@CrossOrigin("*")
public class FileController {

    @Resource
    ImageService imageService;

    /**
     * 上传单文件
     *
     * @param file
     * @param userid
     * @return
     * @throws Exception
     */
    @RequestMapping("/upload")
    public AjaxResult upload(MultipartFile file, String userid) throws Exception {
        Image image = FileUtil.upload(file, userid);
        imageService.insert(image);
        return AjaxResult.success(image);
    }

    /**
     * 上传多文件
     * @param files
     * @param userid
     * @return
     */
    @RequestMapping("/uploads")
    public AjaxResult uploads(@RequestBody List<MultipartFile> files, String userid) {
        List<Image> images = new ArrayList<>();
        files.forEach(file -> {
            try {
                Image image = FileUtil.upload(file, userid);
                imageService.insert(image);
                images.add(image);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        if (images.size() > 0) {
            return AjaxResult.success(images);
        } else {
            return AjaxResult.failure("上传失败");
        }
    }

    /**
     * 下载
     *
     * @param file     下载文件的路径
     * @param response
     * @throws IOException
     */
    @RequestMapping("/download")
    public void download(String file, HttpServletResponse response) throws IOException {
        FileUtil.download(response, file);
    }


    @RequestMapping("/show")
    public AjaxResult show(String userid) {
        List<String> folders = imageService.selectFolderByUserid(userid);
        return folders.size() == 0 ? AjaxResult.failure("查询失败") : AjaxResult.success(folders);
    }


    @RequestMapping("/showPic")
    public AjaxResult pic(String folder, String userid) {
        List<Image> images = imageService.selectByFolderAndUserid(folder, userid);
        return images.size() == 0 ? AjaxResult.failure("查询失败") : AjaxResult.success(images);
    }

    @RequestMapping("/delete")
    public AjaxResult delete(Integer id) {
        int i = imageService.deleteByPrimaryKey(id);
        return i > 0 ? AjaxResult.success() : AjaxResult.failure("删除失败");
    }

    @RequestMapping("/deleteFolder")
    public AjaxResult deleteFolder(String folder) {
        int i = imageService.deleteByFolder(folder);
        return i > 0 ? AjaxResult.success() : AjaxResult.failure("删除失败");
    }

}
